package org.southyin.controller.cms_customer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.southyin.commons.CommonsResp;
import org.southyin.model.CmsCustomer;
import org.southyin.service.CmsCustomerService;
import org.southyin.service.impl.CmsCustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/doLogin")
public class CustomerLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        PrintWriter writer = resp.getWriter();
        if (email == null || email.trim().equals("") || password == null || password.trim().equals("")) {
            CommonsResp commonsResp = CommonsResp.failed(400,"登录邮箱或密码不能为空");
            writer.println(new ObjectMapper().writeValueAsString(commonsResp));
        }else{
            CmsCustomer customer = new CmsCustomer();
            customer.setEmail(email);
            customer.setPassword(password);
            CmsCustomerService service = new CmsCustomerServiceImpl();
            CommonsResp commonsResp = service.customerLogin(customer);
            if (commonsResp.getData() != null) {
                // 获取Session，保存登录者信息
                HttpSession session = req.getSession();
                session.setAttribute("loginer",commonsResp.getData());
            }
            writer.println(new ObjectMapper().writeValueAsString(commonsResp));
        }
    }
}
